<?php

namespace app\admin\controller;

use app\common\BaseHelper;
use app\common\model\Salerule;
use app\lib\exception\ParameterException;

class Sale extends Base
{

    public function Index(){
        $tenantid = session('TENANT_ID');
        $Salerule = new Salerule();
        $sale = $Salerule->where('tenantId',$tenantid)->find();
        if(request()->isAjax()){
            if(!input('post.id')){
                $postdata = input('post.');
                $postdata['id'] = BaseHelper::getUUID();
                $postdata['tenantId'] = $tenantid;
                $Salerule->data($postdata);
                if($Salerule->save()){
                    return show(config('status.SUCCESS_STATUS'),'ok','');
                }
            }else{
                $salerule = $Salerule->where('id',input('post.id'))->find();
                if($salerule->id == $sale->id){
                    $result = $Salerule->save([
                        'value1' => input('post.value1'),
                        'value2' => input('post.value2'),
                        'expIntoDateStr' => input('post.expIntoDateStr'),
                        'qrcodeimg' => input('post.qrcodeimg')
                    ],['id' => input('post.id')]);

                    if($result){
                        return show(config('status.SUCCESS_STATUS'),'ok','');
                    }else{
                        return show(config('status.ERROR_STATUS'),'error','error');
                    }
                }else{
                    throw new ParameterException([
                        'msg' => '数据错误'
                    ]);
                }
            }
        }else{
            if(!$sale){
                $sale['id'] = '';
                $sale['value1'] = '';
                $sale['value2'] = '';
                $sale['expIntoDateStr'] = '';
                $sale['qrcodeimg'] = '';
            }
            $this->assign('sale',$sale);

            return $this->fetch();
        }
    }

}